package com.sansui.blog.controller.admin;

import com.sansui.blog.pojo.User;
import com.sansui.blog.pojo.sys.SysUserRole;
import com.sansui.blog.service.UserService;
import com.sansui.blog.utils.DataResult;
import com.sansui.blog.utils.HttpStatus;
import com.sansui.blog.utils.IpUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name: LoginController
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-03-19 23:52
 **/

/*后台登录控制器类*/
@Controller
@RequestMapping("/admin")
public class LoginController {


    @Autowired
    private UserService userService;

    // 打开登录页
    @GetMapping
    public String loginIndex() {
        return "admin/login";
    }

    @GetMapping("/login")
    public String loginToGet() {
        return "redirect:/admin/index";
    }

    // 登录校验
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes,
                        HttpServletRequest request) throws Exception {

        User user = userService.findByUsername(username);

        if (user == null) {
            attributes.addFlashAttribute("message", "用户信息不存在!");
            return "redirect:/admin";
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            User users = (User) subject.getPrincipal();
            if ("2".equals(users.getStatus())) {
                attributes.addFlashAttribute("message", "该账户已被禁用!");
                return "redirect:/admin";
                //return DataResult.setResult(HttpStatus.SC_ACCEPTED,"该账户禁止登录！");
            }

            if (user.getSysRole().getRoleStatus() != true) {
                //return DataResult.setResult(HttpStatus.SC_ACCEPTED,"该账户角色未开放，请联系管理员！");
                attributes.addFlashAttribute("message", "该账户角色未开放!");
                return "redirect:/admin";
            }

            if (users.getSysRole().getDelFlag() != true) {
                //return DataResult.setResult(HttpStatus.SC_ACCEPTED,"该角色已删除！请联系管理员重新分配。");
                attributes.addFlashAttribute("message", "该角色已删除!");
                return "redirect:/admin";
            }

            //保存登录日志
            String ipAddress = IpUtil.getIpAddr(request);
            Map<String, Object> data = (Map<String, Object>) session.getAttribute("user");

            if (data == null) {
                userService.insertLoginLog(users.getUsername(), ipAddress);
            }

            //存储sessionId
            Map<String, Object> map = new HashMap();
            map.put("token", subject.getSession().getId() + "");
            map.put("uid", users.getUid());
            map.put("username", username);
            map.put("nickname",users.getUserInfo().getNickname());
            session.setAttribute("user", map);
            //return DataResult.setResult(map);
            return "admin/index";
        } catch (Exception e) {
            //return DataResult.setResult(HttpStatus.SC_ACCEPTED,"账号或密码错误！");
            attributes.addFlashAttribute("message", "密码错误!");
//            System.out.println(e.getMessage());
            return "redirect:/admin";
        }
    }

    // 退出登录
    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
//        session.removeAttribute("user");
        return "redirect:/admin";
    }


}
